<?php

namespace App\Http\Rest\Shop\Resource;

use App\Http\Rest\Shop\BaseResource;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Response\ResponseGen;

class Cart
{
    public function __construct()
    {
        session_start();
    }

    public function getList(array $restParams, $request)
    {
        return $this->displayResult();
    }

    public function getInfo(array $restParams, $request)
    {
    }

    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function add(array $restParams, $request)
    {
        return $this->edit($restParams, $request);
    }


    public function edit(array $restParams, $request)
    {
        $productId = $request->getIn('product_id');
        $productNum = $request->getIn('product_num', 1);

        $_SESSION['cart'][$productId] = $productNum;

        if ($productNum == 0 && isset($_SESSION['cart'][$productId])) {
            unset($_SESSION['cart'][$productId]);
        }
        return $this->displayResult();
    }

    public function delete(array $restParams, $request)
    {
        $productId = $request->getIn('product_id');
        if (isset($_SESSION['cart'][$productId])) {
            unset($_SESSION['cart'][$productId]);
        }

        return $this->displayResult();
    }

    public function displayResult()
    {
        $data = [
            'total' => 0,
            'items' => [],
        ];

        if (isset($_SESSION['cart'])) {
            $productIds = array_keys($_SESSION['cart']);
            
            $productList = FDB::from('product')
                ->where('product_id', $productIds)
                ->select(['product_id', 'product_name', 'product_humbnail', 'price'], true)
                ->fetchAll();

            foreach ($productList as $product) {
                $data['items'][$product['product_id']] = $product;
                $data['items'][$product['product_id']]['num'] = $_SESSION['cart'][$product['product_id']];
                $data['total'] += $data['items'][$product['product_id']]['num'] * $product['price'];
            }
        }

        return ResponseGen::success($data);
    }
}
